package jzOffer;

public class Num12 {
    public boolean exist(char[][] board, String word) {
        char[] w=word.toCharArray();
        for(int i=0;i<board.length;i++){
            for(int j=0;j<board[0].length;j++){
                if(dfs(board,w,i,j,0)) return true;
            }
        }
        return false;
    }
    private boolean dfs(char[][] board,char[] w,int i,int j,int k){
        if(i>=board.length || j>=board[0].length || i<0 || j<0 || board[i][j]!=w[k]) return false;
        if(k==w.length-1) return true;
        board[i][j]='\0';
        boolean res=dfs(board,w,i+1,j,k+1) || dfs(board,w,i-1,j,k+1) || dfs(board,w,i,j-1,k+1) || dfs(board,w,i,j+1,k+1);
        board[i][j]=w[k];
        return res;
    }
}

